package cn.piesat.service.impl;

import cn.piesat.mapper.DeptInfoMapper;
import cn.piesat.service.intf.DeptInfoService;
import cn.piesat.util.IPUtil;
import cn.piesat.util.TreeUtil;
import cn.piesat.vo.deptinfo.DeptInfoVO;
import cn.piesat.vo.deptinfo.SaveDeptInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.piesat.dao.PiesatDeptInfoDAO;
import cn.piesat.dao.PiesatUserInfoDAO;
import cn.piesat.dto.PiesatDeptInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门信息逻辑实现
 *
 * @author xhl
 */
@Service
public class DeptInfoServiceImpl implements DeptInfoService {

    @Autowired
    private PiesatDeptInfoDAO piesatDeptInfoDAO;

    @Autowired
    private PiesatUserInfoDAO piesatUserInfoDAO;


    @Override
    public Map<String, String> add(SaveDeptInfoVO saveDeptInfoVO, HttpServletRequest request) {
        Map<String,String> resultMap = new HashMap<>();
        PiesatDeptInfoDTO existDto = piesatDeptInfoDAO.findByName(saveDeptInfoVO.getName());
        if (existDto != null) {
            resultMap.put("success","false");
            resultMap.put("message","该部门名称已经存在");
            return resultMap;
        }
        PiesatDeptInfoDTO piesatDeptInfoDTO = DeptInfoMapper.INSTANCE.saveDeptVo2DeptDto(saveDeptInfoVO);
        piesatDeptInfoDTO.setOperatorIp(IPUtil.getIpAddr(request));
        piesatDeptInfoDTO.setUpdateTime(new Date());
        piesatDeptInfoDAO.save(piesatDeptInfoDTO);
        resultMap.put("success","true");
        resultMap.put("message","添加成功");
        return resultMap;
    }

    @Override
    public Map<String, String> update(SaveDeptInfoVO saveDeptInfoVO, HttpServletRequest request) {
        Map<String,String> resultMap = new HashMap<>();
        PiesatDeptInfoDTO existDto = piesatDeptInfoDAO.findByName(saveDeptInfoVO.getName());
        if (existDto != null && !saveDeptInfoVO.getId().equals(existDto.getId())) {
            resultMap.put("success","false");
            resultMap.put("message","该部门名称已经存在");
            return resultMap;
        }
        PiesatDeptInfoDTO piesatDeptInfoDTO = DeptInfoMapper.INSTANCE.saveDeptVo2DeptDto(saveDeptInfoVO);
        piesatDeptInfoDTO.setOperatorIp(IPUtil.getIpAddr(request));
        piesatDeptInfoDTO.setUpdateTime(new Date());
        piesatDeptInfoDAO.save(piesatDeptInfoDTO);
        resultMap.put("success","true");
        resultMap.put("message","修改成功");
        return resultMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> del(String id) {
        Map<String,String> resultMap = new HashMap<>();
        List<PiesatDeptInfoDTO> allList = piesatDeptInfoDAO.findAll();
        JSONArray jsonArray = TreeUtil.listToTree(JSON.parseArray(JSON.toJSONString(allList)), "id", "prentId", "children");
        JSONObject jsonObject = recursionTree(jsonArray, id);
        if (jsonObject != null) {
            List<String> idList = new ArrayList<>();
            idList.add(jsonObject.getString("id"));
            if (jsonObject.containsKey("children")) {
                recursionAddId(jsonObject.getJSONArray("children"),idList);
            }
            piesatDeptInfoDAO.deleteAllByIdIn(idList);
            //清除用户绑定的部门信息
            piesatUserInfoDAO.updateDeptIn(idList);
            resultMap.put("success","true");
            resultMap.put("message","删除成功");
            return resultMap;
        }
        resultMap.put("success","false");
        resultMap.put("message","删除的信息不存在");
        return resultMap;
    }

    @Override
    public PiesatDeptInfoDTO findById(String id) {
        return piesatDeptInfoDAO.findById(id).orElse(null);
    }

    @Override
    public JSONArray getAll() {
        List<PiesatDeptInfoDTO> allList = piesatDeptInfoDAO.findAllByOrderBySeq();
        List<DeptInfoVO> dataList = allList
                .stream()
                .map(DeptInfoMapper.INSTANCE::deptInfoDto2DeptInfoVo)
                .collect(Collectors.toList());
        return TreeUtil.listToTree(JSON.parseArray(JSON.toJSONString(dataList)), "id", "prentId", "children");
    }

    private JSONObject recursionTree(JSONArray jsonArray, String id) {
        JSONObject j = null;
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject)o;
            if (jsonObject.getString("id").equals(id)) {
                return jsonObject;
            }
            if (jsonObject.containsKey("children")) {
                j = recursionTree(jsonObject.getJSONArray("children"),id);
            }
        }
        return j;
    }

    private void recursionAddId(JSONArray jsonArray,List<String> idList) {
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject)o;
            if (jsonObject.containsKey("children")) {
                recursionAddId(jsonObject.getJSONArray("children"),idList);
            }
            idList.add(jsonObject.getString("id"));
        }
    }
}
